var webpack = require('webpack');
var path = require('path');
var glob = require('glob');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'build');
var TEM_PATH = path.resolve(ROOT_PATH, 'templates');

var getEntries = function (APP_PATH) {
    var all = glob.sync(path.resolve(APP_PATH, '**/index.js'), {
        ignore: path.resolve(APP_PATH, 'global/**/*.js')
    });
    const obj = {};
    for (var i = 0; i < all.length; i++) {
        var resolvePath = path.resolve(all[i]);
        var relativePath = path.relative(APP_PATH, resolvePath);
        var dirname = path.dirname(relativePath);
        var basename = path.basename(resolvePath);
        var afterPath = path.join(BUILD_PATH, dirname, basename);
        obj[dirname] = resolvePath;
    }
    return obj;
}
var entries = getEntries(APP_PATH);
entries.vendors = ['jquery', 'moment'];

var plugins = [new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js')];
for (var name in entries) {
    if(name=='vendors'){
        break;
    }
    // 每个页面生成一个html
    var plugin = new HtmlwebpackPlugin({
        // 生成出来的html文件名
        filename: name + '.html',
        // 每个html的模版，这里多个页面使用同一个模版
        template: 'templates/'+name + '.html',
        // 自动将引用插入html
        inject: 'head',
        // 每个html引用的js模块，也可以在这里加上vendor等公用模块
        chunks: [name,'vendors']
    });
    plugins.push(plugin);
}
module.exports = {
    //项目的文件夹 可以直接用文件夹名称 默认会找index.js 也可以确定是哪个文件名字
    entry: entries,
    // {
    //     app: path.resolve(APP_PATH, 'index.js'),
    //     mobile: path.resolve(APP_PATH, 'mobile.js'),
    //     //添加要打包在vendors里面的库
    //     vendors: ['jquery', 'moment']
    // }
    //,
    //输出的文件名 合并以后的js会命名为bundle.js
    output: {
        path: BUILD_PATH,
        filename: '[name].min.js'
    },
    module: {
        preLoaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'eslint-loader'
        }],
        loaders: [{
            test: /\.jsx?$/,
            include: APP_PATH,
            loader: 'babel',
            query: {
                presets: ['es2015']
            }
        }, {
            test: /\.(png|jpg|gif)$/,
            loader: 'url-loader?limit=8192' // 这里的 limit=8192 表示用 base64 编码 <= ８K 的图像
        }, {
            test: /\.css$/,
            loader: 'style!css'
        }, {
            test: /\.less$/,
            loader: 'style!css!less'
        }, ]
    },
    //添加我们的插件 会自动生成一个html文件
    plugins: plugins,
    devtool: 'source-map',
    devServer: {
        historyApiFallback: true,
        hot: false,
        inline: true,
        progress: true,
    },
    eslint: {
        configFile: './.eslintrc'
    }
};